package com.example.spring_mybatis.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.spring_mybatis.dto.UserDTO;
import com.example.spring_mybatis.model.UserEntity;
import com.example.spring_mybatis.service.IUserService;
import com.example.spring_mybatis.utils.RUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService iUserService;

    @PostMapping("")
    public RUtil<String> createUser(@RequestBody UserDTO userDto) {
        log.info("进入创建用户的控制器");
        return this.iUserService.createUser(userDto);
    }

    @GetMapping()
    public RUtil<List<UserEntity>> getUser() {
        List<UserEntity> list = this.iUserService.list();
        return RUtil.success(list);
    }

    @GetMapping("/{id}")
    public RUtil<UserEntity> getUserById(@PathVariable Long id) {
        UserEntity userEntity = this.iUserService.getById(id);
        return RUtil.success(userEntity);
    }

    @PutMapping("/{id}")
    public RUtil<String> modifyUserById(@PathVariable Long id, @RequestBody UserDTO userDto) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto, userEntity);
        userEntity.setId(id);
        iUserService.updateById(userEntity);
        return RUtil.success("更新成功");
    }



    @GetMapping("/page")
    public RUtil<Page<UserEntity>> page(@RequestParam Long pageNumber, @RequestParam Long pageSize) {
        System.out.println("进入分页查询");
        Page<UserEntity> pageParams = new Page<>(pageNumber, pageSize);
        return RUtil.success(iUserService.page(pageParams));
    }
}
